# encoding: utf-8
from __future__ import unicode_literals

from datetime import timedelta

from django.contrib.admin.filters import FieldListFilter
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _


class MonthFilter(FieldListFilter):
    def has_output(self):
        return super(MonthFilter, self).has_output()

    def __init__(self, field, request, params, model, model_admin, field_path):
        self.field_generic = '%s__' % field_path
        self.date_params = dict([(k, v) for k, v in params.items()
                                 if k.startswith(self.field_generic)])

        now = timezone.now()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        if isinstance(field, models.DateTimeField):
            today = now.replace(hour=0, minute=0, second=0, microsecond=0)
        else:  # field is a models.DateField
            today = now.date()
        tomorrow = today + timedelta(days=1)
        if today.month == 12:
            end_month = today.replace(year=today.year + 1, month=1, day=1)
        else:
            end_month = today.replace(month=today.month + 1, day=1)
        end_year = today.replace(year=today.year + 1, month=1, day=1)

        self.lookup_kwarg_since = '%s__gte' % field_path
        self.lookup_kwarg_until = '%s__lt' % field_path
        self.links = (
            (_('Any date'), {}),
        )
        start_month = today.replace(day=1)
        for i in range(0, 12):
            self.links += ((u'%d年%02d月' % (start_month.year, start_month.month), {
                self.lookup_kwarg_since: str(start_month),
                self.lookup_kwarg_until: str(end_month),
            }),)
            end_month = start_month
            if start_month.month == 1:
                start_month = start_month.replace(year=start_month.year - 1, month=12)
            else:
                start_month = start_month.replace(month=start_month.month - 1)
        start_year = today.replace(month=1, day=1)
        for i in range(0, 2):
            self.links += ((u'%d全年度' % start_year.year, {
                self.lookup_kwarg_since: str(start_year),
                self.lookup_kwarg_until: str(end_year),
            }),)
            end_year = start_year
            start_year = start_year.replace(year=start_year.year - 1)

        super(MonthFilter, self).__init__(
            field, request, params, model, model_admin, field_path)

    def expected_parameters(self):
        return [self.lookup_kwarg_since, self.lookup_kwarg_until]

    def choices(self, cl):
        for title, param_dict in self.links:
            yield {
                'selected': self.date_params == param_dict,
                'query_string': cl.get_query_string(param_dict, [self.field_generic]),
                'display': title,
            }
